<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Routes_model extends WS_model
{
    public function updateMissingKeys($grouping_id, $language_id)
    {
        $this->db->select("r.route_seq_id,$language_id as language_seq_id,r.route_default_key,r.route_default_value,r.route_default_url_structure");
        $this->db->from('routes r');
        $this->db->join('routes_values rv', "rv.route_seq_id = r.route_seq_id AND rv.language_seq_id = $language_id", 'left');
        $this->db->where('rv.rv_seq_id IS NULL');
        $this->db->where('r.lg_seq_id', $grouping_id);
        $select_sql = $this->sql();
        $sql = "INSERT INTO ws_routes_values (
                    route_seq_id,
                    language_seq_id,
                    route_key,
                    route_value,
                    route_url_struture
                )({$select_sql})";
        $this->db->query($sql);
    }

    public function groupsOfGroupingLanguage($grouping_id, $language_id)
    {
        $this->db->from('routes_values rv');
        $this->db->join('routes r', 'rv.route_seq_id = r.route_seq_id', 'left');
        $this->db->where('r.lg_seq_id', $grouping_id);
        $this->db->where('rv.language_seq_id', $language_id);
        $this->db->order_by('rv.route_key', 'asc');
        $this->db->order_by('rv.route_key', 'asc');
        return $this->result();
    }

    public function update($data, $key = false)
    {
        if (!$key)
            $this->db->update('routes_values', $data);
        else
            $this->db->update_batch('routes_values', $data, $key);
        return $this->db->affected_rows();
    }

    public function get_routes()
    {
        $this->db->select('rv.route_key, r.route_controller, rv.route_value,r.route_name,rv.route_url_struture', false);
        $this->db->from('routes_values rv');
        $this->db->join('routes r', 'r.route_seq_id = rv.route_seq_id', 'left');
        $this->db->join('language_grouping lg', 'lg.lg_seq_id = r.lg_seq_id AND rv.language_seq_id = lg.language_seq_id', 'left');
        $this->db->where('lg.language_seq_id IS NOT NULL', false, false);
        $this->db->order_by('LENGTH(rv.route_key)', 'desc');
        return $this->result();
    }
}